<?php


namespace App\Http\Controllers\Mp;


use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Model\Device;
use App\Model\Message;
use App\Model\Repair;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    public function index(Request $request)
    {
        // Get the current page number from the request parameters (default to 1)
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = 20;

        $query = Message::query();
        $query->where('user_id', Token::getUser()->id);

        $data = $query->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new PaginationCollection($data));
    }

    public function read(Request $request)
    {
        if ($request->has('id')) {
            $msg = Message::find($request->input('id'));
            $msg->is_read = 1;
            $msg->save();
        } else {
            Message::query()->where('user_id', Token::getUser()->id)->update(['is_read' => 1]);
        }
        return Result::success();
    }

    public function flush()
    {
        Message::query()->where('user_id', Token::getUser()->id)->delete();
        return Result::success();
    }
}
